<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 角色数据列表区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe style="width: 100%">
        <!-- 展开列表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdBottom',i1==0?'bdTop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限的展示 -->
              <el-col :span="8">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
              </el-col>
              <!-- 二级或三级权限的展示 -->
              <el-col :span="16">
                <el-row
                  :class="[i2 === 0 ?'':'bdTop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      @close="removeRightById(scope.row,item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="info" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-setting"
              @click="showSetDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allowSettingVisible"
      width="60%"
      @close="setRightDailogClosed"
    >
      <!-- 显示所有的权限 -->
      <el-tree
        :data="rightsList"
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="rightsCheckedKeys"
        show-checkbox
        :props="treeRightsProp"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allowSettingVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      allowSettingVisible: false,
      rightsCheckedKeys: [],
      rightsList: [],
      treeRightsProp: {
        children: 'children',
        label: 'authName'
      },
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户角色失败')
      }
      this.roleList = res.data
    },
    async removeRightById(role, rightId) {
      const confirmDialog = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmDialog !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // 删除角色指定权限接口
      // 请求路径：roles/:roleId/rights/:rightId
      // 请求方法: delete
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除权限成功')
      // this.getRoleList(); 调用此方法页面会重新渲染刷新
      role.children = res.data // 数据更新防治页面刷新
    },
    // 展示分配权限的对话框
    async showSetDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }

      this.rightsList = res.data
      // 递归获取三级节点集合
      this.getLeaf(role, this.rightsCheckedKeys)
      this.allowSettingVisible = true
    },
    // 通过递归获取三级节点
    getLeaf(node, arr) {
      // 没有孩子节点就是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeaf(item, arr)
      })
    },
    setRightDailogClosed() {
      this.rightsCheckedKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ] // [1,2,3,4]
      const idStr = keys.join(',') // 1,2,3,4,

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$messge.error('修改权限失败')
      }

      this.$message.success('成功修改权限失败')
      this.getRoleList()
      this.allowSettingVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 5px;
}
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #eee;
}

.bdBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
